<template>
  <div>
    <n-data-table :columns="columns" :data="list" :row-key="(row) => row['id'] || row['mid']" />
    <n-flex justify="end" class="mt-10">
      <n-button ghost type="primary" size="small" @click="methods.addMember">
        <i class="i-material-symbols:add mr-4 text-18" />
        添加
      </n-button>
    </n-flex>
  </div>
</template>
<script setup lang="jsx">
import { getSelArrDicts } from '@/api/dict'
import { userSel } from '@/api/user'

defineOptions({ name: 'Member' })
const props = defineProps({
  groupId: {
    type: String,
    default: '',
  },
})
const list = defineModel({
  type: Array,
  default: () => [],
})

const rangeOptions = ref([])
const columns = [
  {
    title: '序号',
    width: 60,
    key: 'index',
    render: (_, index) => index + 1,
  },
  {
    title: '人员',
    key: 'personId',
    width: 180,
    render: ({ personId, id }, index) => (
      <AsyncSelect
        options={methods.getUserOptions}
        value={personId}
        label-key="name"
        value-key="userId"
        remote={true}
        init-remote={true}
        onUpdateValue={(_, item) => methods.onChangePerson(index, item)}
        disabled={Boolean(id)}
      />
    ),
  },
  {
    title: '组别',
    key: 'groupName',
    width: 80,
  },
  {
    title: '岗位',
    key: 'positionName',
    width: 80,
  },
  {
    title: '执行',
    key: 'executeName',
    width: 60,
  },
  {
    title: '执行范围',
    key: 'executeRangeCode',
    width: 320,
    render: ({ executeRangeCode }, index) => (
      <AsyncSelect
        options={rangeOptions.value}
        multiple={true}
        value={executeRangeCode}
        label-key="name"
        value-key="code"
        onUpdate:value={(val) => methods.onChangeRange(index, val)}
      />
    ),
  },
  {
    title: '产品负责人',
    key: 'isProductHeader',
    width: 100,
    render: ({ isProductHeader }, index) => (
      <n-checkbox
        checked={isProductHeader}
        checked-value={true}
        unchecked-value={false}
        onUpdate:checked={(val) => methods.onChangeCheck(index, val)}
      />
    ),
  },
  {
    title: '操作',
    key: 'actions',
    width: 60,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row, index) {
      return (
        <n-button
          text
          onClick={() => methods.removeMember(index)}
          disabled={Boolean(row.isHaveTask)}
        >
          删除
        </n-button>
      )
    },
  },
]
const methods = reactive({
  async getRangeOptions() {
    rangeOptions.value = await getSelArrDicts({ codes: 'EXECUTE_RANGE' }).then(
      (res) => res.data.EXECUTE_RANGE
    )
  },
  getUserOptions(name, userId) {
    return userSel({ name, userId }).then((res) => res.data)
  },
  memberMold() {
    return {
      personId: null,
      groupCode: null,
      groupName: null,
      positionName: null,
      executeName: null,
      executeRangeCode: [],
      isDevelopmentMember: false,
      mid: Date.now(),
      isProductHeader: 0,
    }
  },
  onChangePerson(index, item) {
    const {
      userId: personId,
      deptId: groupCode,
      deptName: groupName,
      isLeader,
      isDevelopmentMember,
      isSeniorExecutive,
    } = item || {}
    const data = {
      personId,
      groupCode,
      groupName,
      isDevelopmentMember,
      positionName: !personId ? '' : isSeniorExecutive ? '高管' : isLeader ? '组长' : '组员',
      executeName: methods.judgeDuty(personId, groupCode, isDevelopmentMember),
      executeRangeCode: [],
    }
    Object.entries(data).forEach(([key, val]) => (list.value[index][key] = val))
  },
  onChangeRange(index, val) {
    list.value[index].executeRangeCode = val
  },
  onChangeCheck(index, val) {
    list.value.forEach((item) => {
      item['isProductHeader'] = false
    })
    list.value[index].isProductHeader = val
  },
  addMember() {
    list.value.push(methods.memberMold())
  },
  removeMember(index) {
    list.value.splice(index, 1)
  },
  judgeDuty(personId, groupCode, isDevelopmentMember) {
    if (personId) {
      if (isDevelopmentMember) {
        return groupCode === props.groupId ? '负责' : '协助'
      } else {
        return '负责'
      }
    } else {
      return ''
    }
  },
})
onBeforeMount(() => {
  methods.getRangeOptions()
})
watch(
  () => props.groupId,
  () => {
    list.value = list.value.map((item) => ({
      ...item,
      executeName: methods.judgeDuty(item.personId, item.groupCode, item.isDevelopmentMember),
    }))
  }
)
</script>
<style lang="scss" scoped></style>
